"""
告警管理系统主服务
集成告警规则引擎、通知系统和工作流管理，提供统一的告警管理接口
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any
from uuid import uuid4

from services.alerts.alert_rules_engine import AlertRulesEngine
from services.alerts.alert_notification_service import AlertNotificationService
from services.alerts.alert_workflow_service import AlertWorkflowService
from schemas.alert_management import (
    AlertEvent, AlertRule, AlertRuleCreateRequest, AlertRuleUpdateRequest,
    AlertEventUpdateRequest, AlertQuery, AlertStatistics, NotificationTemplate,
    NotificationConfig, AlertLevel, AlertCategory, AlertStatus
)

logger = logging.getLogger(__name__)


class AlertManagementService:
    """告警管理系统主服务"""
    
    def __init__(self):
        self.rules_engine = AlertRulesEngine()
        self.notification_service = AlertNotificationService()
        self.workflow_service = AlertWorkflowService()
        
        # 服务状态
        self.is_running = False
        self.background_tasks = []
        
        # 性能统计
        self.performance_stats = {
            'alerts_processed': 0,
            'rules_evaluated': 0,
            'notifications_sent': 0,
            'workflow_actions': 0,
            'processing_time_ms': 0.0
        }
        
        # 系统异常告警缓存
        self.system_alerts_cache = {}
        self.system_alert_cooldowns = {}
    
    async def start_service(self):
        """启动告警管理服务"""
        if self.is_running:
            return
        
        self.is_running = True
        
        # 启动通知服务
        await self.notification_service.start_services()
        
        # 启动后台任务
        self.background_tasks = [
            asyncio.create_task(self.workflow_service.start_escalation_monitor()),
            asyncio.create_task(self._performance_monitor())
        ]
        
        logger.info("告警管理服务已启动")
    
    async def stop_service(self):
        """停止告警管理服务"""
        if not self.is_running:
            return
        
        self.is_running = False
        
        # 停止后台任务
        for task in self.background_tasks:
            task.cancel()
        
        # 停止通知服务
        await self.notification_service.stop_services()
        
        logger.info("告警管理服务已停止")
    
    # ==================== 告警规则管理 ====================
    
    async def create_alert_rule(self, rule_request: AlertRuleCreateRequest) -> AlertRule:
        """创建告警规则"""
        return await self.rules_engine.add_rule(rule_request)
    
    async def update_alert_rule(self, rule_id: str, rule_request: AlertRuleUpdateRequest) -> Optional[AlertRule]:
        """更新告警规则"""
        return await self.rules_engine.update_rule(rule_id, rule_request)
    
    async def delete_alert_rule(self, rule_id: str) -> bool:
        """删除告警规则"""
        return await self.rules_engine.delete_rule(rule_id)
    
    async def get_alert_rule(self, rule_id: str) -> Optional[AlertRule]:
        """获取告警规则"""
        return await self.rules_engine.get_rule(rule_id)
    
    async def list_alert_rules(self, category: Optional[AlertCategory] = None,
                              enabled_only: bool = True) -> List[AlertRule]:
        """列出告警规则"""
        return await self.rules_engine.list_rules(category, enabled_only)
    
    # ==================== 告警事件处理 ====================
    
    async def process_data(self, data: Dict[str, Any]) -> List[AlertEvent]:
        """处理数据并生成告警"""
        start_time = datetime.now()
        
        try:
            # 使用规则引擎评估数据
            generated_alerts = await self.rules_engine.evaluate_data(data)
            
            # 处理生成的告警
            processed_alerts = []
            for alert in generated_alerts:
                # 添加到工作流
                alert = await self.workflow_service.add_alert(alert)
                
                # 发送通知
                notifications = await self.notification_service.send_alert_notifications(alert)
                
                processed_alerts.append(alert)
                
                logger.info(f"处理告警: {alert.alert_id}, 发送通知: {len(notifications)}条")
            
            # 更新性能统计
            processing_time = (datetime.now() - start_time).total_seconds() * 1000
            self.performance_stats['alerts_processed'] += len(processed_alerts)
            self.performance_stats['processing_time_ms'] += processing_time
            
            return processed_alerts
            
        except Exception as e:
            logger.error(f"处理数据时发生错误: {e}")
            return []
    
    async def get_alert(self, alert_id: str) -> Optional[AlertEvent]:
        """获取告警详情"""
        return self.workflow_service.alerts.get(alert_id)
    
    async def update_alert(self, alert_id: str, update_request: AlertEventUpdateRequest,
                          user_id: str) -> bool:
        """更新告警"""
        alert = self.workflow_service.alerts.get(alert_id)
        if not alert:
            return False
        
        # 处理状态更新
        if update_request.status:
            if update_request.status == AlertStatus.ACKNOWLEDGED:
                return await self.workflow_service.acknowledge_alert(alert_id, user_id)
            elif update_request.status == AlertStatus.RESOLVED:
                resolution_note = update_request.resolution_note or "已解决"
                return await self.workflow_service.resolve_alert(alert_id, user_id, resolution_note)
            elif update_request.status == AlertStatus.CLOSED:
                return await self.workflow_service.close_alert(alert_id, user_id)
        
        # 处理分配更新
        if update_request.assigned_to:
            return await self.workflow_service.assign_alert(alert_id, update_request.assigned_to, user_id)
        
        # 处理标签更新
        if update_request.tags is not None:
            alert.tags = update_request.tags
            return True
        
        return False
    
    async def query_alerts(self, query: AlertQuery) -> List[AlertEvent]:
        """查询告警"""
        return await self.workflow_service.query_alerts(query)
    
    # ==================== 告警工作流操作 ====================
    
    async def assign_alert(self, alert_id: str, assignee: str, user_id: str) -> bool:
        """分配告警"""
        return await self.workflow_service.assign_alert(alert_id, assignee, user_id)
    
    async def acknowledge_alert(self, alert_id: str, user_id: str, note: Optional[str] = None) -> bool:
        """确认告警"""
        return await self.workflow_service.acknowledge_alert(alert_id, user_id, note)
    
    async def resolve_alert(self, alert_id: str, user_id: str, resolution_note: str) -> bool:
        """解决告警"""
        return await self.workflow_service.resolve_alert(alert_id, user_id, resolution_note)
    
    async def close_alert(self, alert_id: str, user_id: str, close_note: Optional[str] = None) -> bool:
        """关闭告警"""
        return await self.workflow_service.close_alert(alert_id, user_id, close_note)
    
    async def escalate_alert(self, alert_id: str, escalation_target: str, user_id: str,
                           escalation_reason: str) -> bool:
        """升级告警"""
        return await self.workflow_service.escalate_alert(
            alert_id, escalation_target, user_id, escalation_reason
        )
    
    async def reopen_alert(self, alert_id: str, user_id: str, reopen_reason: str) -> bool:
        """重新打开告警"""
        return await self.workflow_service.reopen_alert(alert_id, user_id, reopen_reason)
    
    async def add_alert_comment(self, alert_id: str, user_id: str, comment: str) -> bool:
        """添加告警评论"""
        return await self.workflow_service.add_comment(alert_id, user_id, comment)
    
    # ==================== 通知管理 ====================
    
    async def add_notification_template(self, template: NotificationTemplate):
        """添加通知模板"""
        await self.notification_service.add_template(template)
    
    async def add_notification_config(self, config: NotificationConfig):
        """添加通知配置"""
        await self.notification_service.add_config(config)
    
    def configure_email_notifications(self, smtp_host: str, smtp_port: int,
                                    username: str, password: str, use_tls: bool = True):
        """配置邮件通知"""
        self.notification_service.configure_email_channel(
            smtp_host, smtp_port, username, password, use_tls
        )
    
    def configure_sms_notifications(self, api_url: str, api_key: str, api_secret: str):
        """配置短信通知"""
        self.notification_service.configure_sms_channel(api_url, api_key, api_secret)
    
    def configure_webhook_notifications(self):
        """配置Webhook通知"""
        self.notification_service.configure_webhook_channel()
    
    def configure_websocket_notifications(self):
        """配置WebSocket通知"""
        self.notification_service.configure_websocket_channel()
    
    def configure_mobile_push_notifications(self, push_service_url: str, app_key: str, app_secret: str):
        """配置移动推送通知"""
        self.notification_service.configure_mobile_push_channel(push_service_url, app_key, app_secret)
    
    # ==================== 统计和报表 ====================
    
    async def get_alert_statistics(self, start_time: Optional[datetime] = None,
                                 end_time: Optional[datetime] = None) -> AlertStatistics:
        """获取告警统计"""
        return await self.workflow_service.get_alert_statistics(start_time, end_time)
    
    async def get_dashboard_data(self) -> Dict[str, Any]:
        """获取仪表板数据"""
        # 获取基础统计
        stats = await self.get_alert_statistics()
        
        # 获取最近24小时的告警趋势
        now = datetime.now()
        last_24h = now - timedelta(hours=24)
        recent_alerts = await self.query_alerts(AlertQuery(
            start_time=last_24h,
            end_time=now,
            limit=1000
        ))
        
        # 按小时分组
        hourly_counts = {}
        for i in range(24):
            hour = (now - timedelta(hours=i)).strftime("%H:00")
            hourly_counts[hour] = 0
        
        for alert in recent_alerts:
            hour = alert.created_at.strftime("%H:00")
            if hour in hourly_counts:
                hourly_counts[hour] += 1
        
        # 获取活跃告警
        active_alerts = await self.query_alerts(AlertQuery(
            statuses=[AlertStatus.ACTIVE, AlertStatus.ACKNOWLEDGED],
            limit=50
        ))
        
        # 获取用户工作负载
        user_workload = self.workflow_service.user_workload
        
        return {
            'statistics': stats.dict(),
            'hourly_trend': hourly_counts,
            'active_alerts': [alert.dict() for alert in active_alerts],
            'user_workload': dict(user_workload),
            'service_status': {
                'rules_engine': self.rules_engine.get_engine_stats(),
                'notification_service': self.notification_service.get_notification_stats(),
                'workflow_service': self.workflow_service.get_service_stats()
            }
        }
    
    async def get_performance_metrics(self) -> Dict[str, Any]:
        """获取性能指标"""
        return {
            **self.performance_stats,
            'avg_processing_time_ms': (
                self.performance_stats['processing_time_ms'] / 
                max(1, self.performance_stats['alerts_processed'])
            ),
            'service_uptime': self.is_running,
            'background_tasks': len(self.background_tasks)
        }
    
    # ==================== 批量操作 ====================
    
    async def bulk_assign_alerts(self, alert_ids: List[str], assignee: str, user_id: str) -> Dict[str, bool]:
        """批量分配告警"""
        results = {}
        for alert_id in alert_ids:
            results[alert_id] = await self.assign_alert(alert_id, assignee, user_id)
        return results
    
    async def bulk_resolve_alerts(self, alert_ids: List[str], user_id: str, 
                                resolution_note: str) -> Dict[str, bool]:
        """批量解决告警"""
        results = {}
        for alert_id in alert_ids:
            results[alert_id] = await self.resolve_alert(alert_id, user_id, resolution_note)
        return results
    
    async def bulk_close_alerts(self, alert_ids: List[str], user_id: str,
                              close_note: Optional[str] = None) -> Dict[str, bool]:
        """批量关闭告警"""
        results = {}
        for alert_id in alert_ids:
            results[alert_id] = await self.close_alert(alert_id, user_id, close_note)
        return results
    
    # ==================== 内部方法 ====================
    
    async def _performance_monitor(self):
        """性能监控"""
        while self.is_running:
            try:
                # 记录性能指标
                engine_stats = self.rules_engine.get_engine_stats()
                notification_stats = self.notification_service.get_notification_stats()
                workflow_stats = self.workflow_service.get_service_stats()
                
                self.performance_stats['rules_evaluated'] = engine_stats['rules_evaluated']
                self.performance_stats['notifications_sent'] = notification_stats['notifications_sent']
                self.performance_stats['workflow_actions'] = sum(workflow_stats['workflow_actions'].values())
                
                # 每5分钟记录一次性能日志
                logger.info(f"告警管理服务性能: {self.performance_stats}")
                
                await asyncio.sleep(300)  # 5分钟
                
            except Exception as e:
                logger.error(f"性能监控错误: {e}")
                await asyncio.sleep(60)
    
    # ==================== 预设配置 ====================
    
    async def setup_default_templates(self):
        """设置默认通知模板"""
        # 邮件模板
        email_template = NotificationTemplate(
            template_id="default_email",
            name="默认邮件模板",
            channel="email",
            subject_template="告警通知: {title}",
            body_template="""
            <h2>告警通知</h2>
            <p><strong>告警标题:</strong> {title}</p>
            <p><strong>告警级别:</strong> {level}</p>
            <p><strong>告警类别:</strong> {category}</p>
            <p><strong>告警消息:</strong> {message}</p>
            <p><strong>发生时间:</strong> {created_at}</p>
            <p><strong>位置:</strong> {location}</p>
            {if camera_id}<p><strong>摄像头:</strong> {camera_id}</p>{/if}
            {if classroom_id}<p><strong>教室:</strong> {classroom_id}</p>{/if}
            {if teacher_id}<p><strong>教师:</strong> {teacher_id}</p>{/if}
            """,
            variables=["title", "level", "category", "message", "created_at", "location", "camera_id", "classroom_id", "teacher_id"]
        )
        
        # 短信模板
        sms_template = NotificationTemplate(
            template_id="default_sms",
            name="默认短信模板",
            channel="sms",
            subject_template="告警通知",
            body_template="告警: {title} | 级别: {level} | 位置: {location} | 时间: {created_at}",
            variables=["title", "level", "location", "created_at"]
        )
        
        # WebSocket模板
        websocket_template = NotificationTemplate(
            template_id="default_websocket",
            name="默认WebSocket模板",
            channel="websocket",
            subject_template="告警通知",
            body_template="{title} - {message}",
            variables=["title", "message"]
        )
        
        await self.add_notification_template(email_template)
        await self.add_notification_template(sms_template)
        await self.add_notification_template(websocket_template)
        
        logger.info("默认通知模板已设置")
    
    async def setup_default_configs(self):
        """设置默认通知配置"""
        # 高级告警配置
        critical_config = NotificationConfig(
            config_id="critical_alerts",
            name="严重告警通知",
            channels=["email", "sms", "websocket"],
            recipients=["admin@example.com", "13800138000"],
            alert_levels=[AlertLevel.CRITICAL],
            alert_categories=[],
            template_mapping={
                "email": "default_email",
                "sms": "default_sms",
                "websocket": "default_websocket"
            }
        )
        
        # 一般告警配置
        general_config = NotificationConfig(
            config_id="general_alerts",
            name="一般告警通知",
            channels=["websocket"],
            recipients=["operator@example.com"],
            alert_levels=[AlertLevel.HIGH, AlertLevel.MEDIUM],
            alert_categories=[],
            time_windows=[{
                "start_time": "08:00",
                "end_time": "18:00",
                "weekdays": ["monday", "tuesday", "wednesday", "thursday", "friday"]
            }],
            template_mapping={
                "websocket": "default_websocket"
            }
        )
        
        await self.add_notification_config(critical_config)
        await self.add_notification_config(general_config)
        
        logger.info("默认通知配置已设置")
    
    # ==================== 实时告警处理 ====================
    
    async def process_real_time_alert(self, alert_data: Dict[str, Any]) -> bool:
        """处理实时告警数据"""
        try:
            # 发送到智能告警服务处理
            success = await self.rules_engine.process_real_time_result(alert_data)
            
            if success:
                # 直接发送实时推送
                await self.notification_service.send_real_time_alert(alert_data)
                
                # 更新统计
                self.performance_stats['alerts_processed'] += 1
            
            return success
            
        except Exception as e:
            logger.error(f"处理实时告警失败: {e}")
            return False
    
    async def process_batch_real_time_alerts(self, alerts_data: List[Dict[str, Any]]) -> int:
        """批量处理实时告警"""
        success_count = 0
        
        for alert_data in alerts_data:
            if await self.process_real_time_alert(alert_data):
                success_count += 1
        
        logger.info(f"批量处理实时告警: {success_count}/{len(alerts_data)} 成功")
        return success_count
    
    def setup_real_time_monitoring(self):
        """设置实时监控"""
        # 配置WebSocket通知
        self.configure_websocket_notifications()
        
        # 设置默认实时规则
        self.rules_engine.setup_default_real_time_rules()
        
        logger.info("实时监控已设置")
    
    async def get_real_time_dashboard(self) -> Dict[str, Any]:
        """获取实时监控仪表板数据"""
        # 获取实时统计
        real_time_stats = await self.rules_engine.get_real_time_statistics()
        
        # 获取通知统计
        notification_stats = self.notification_service.get_notification_stats()
        
        # 获取最近的活跃告警
        recent_alerts = await self.query_alerts(AlertQuery(
            start_time=datetime.now() - timedelta(minutes=30),
            statuses=[AlertStatus.ACTIVE, AlertStatus.ACKNOWLEDGED],
            limit=20
        ))
        
        return {
            'real_time_stats': real_time_stats,
            'notification_stats': notification_stats,
            'recent_alerts': [alert.dict() for alert in recent_alerts],
            'service_performance': self.performance_stats,
            'system_status': {
                'service_running': self.is_running,
                'websocket_connections': len(getattr(
                    self.notification_service.channels.get('websocket', {}), 
                    'connections', {}
                )),
                'active_rules': len([
                    r for r in self.rules_engine.alert_rules.values() 
                    if r.enabled
                ])
            }
        }
    
    # ==================== WebSocket连接管理 ====================
    
    def add_websocket_connection(self, user_id: str, websocket):
        """添加WebSocket连接"""
        self.notification_service.add_websocket_connection(user_id, websocket)
    
    def remove_websocket_connection(self, user_id: str):
        """移除WebSocket连接"""
        self.notification_service.remove_websocket_connection(user_id)
    
    def join_monitoring_room(self, user_id: str, room: str = "monitoring"):
        """加入监控房间"""
        self.notification_service.join_monitoring_room(user_id, room)
    
    def leave_monitoring_room(self, user_id: str, room: str = "monitoring"):
        """离开监控房间"""
        self.notification_service.leave_monitoring_room(user_id, room)
    
    async def broadcast_system_status(self, status_message: str) -> int:
        """广播系统状态消息"""
        return await self.notification_service.broadcast_system_message(
            status_message, "monitoring"
        )
    
    # ==================== 系统异常告警扩展 ====================
    
    async def create_system_alert(self, alert_type: str, message: str, severity: str = "warning", 
                                 metadata: Optional[Dict[str, Any]] = None) -> str:
        """创建系统异常告警"""
        try:
            # 检查冷却时间
            current_time = datetime.now()
            cooldown_key = f"{alert_type}_{severity}"
            
            if cooldown_key in self.system_alert_cooldowns:
                last_alert_time = self.system_alert_cooldowns[cooldown_key]
                time_diff = (current_time - last_alert_time).total_seconds()
                
                # 根据严重程度设置不同的冷却时间
                cooldown_seconds = {
                    "critical": 60,    # 1分钟
                    "warning": 300,    # 5分钟
                    "info": 600        # 10分钟
                }.get(severity, 300)
                
                if time_diff < cooldown_seconds:
                    logger.debug(f"系统告警 {alert_type} 在冷却期内，跳过")
                    return ""
            
            # 创建告警事件
            alert_id = str(uuid4())
            alert_event = AlertEvent(
                alert_id=alert_id,
                title=f"系统异常: {alert_type}",
                message=message,
                level=AlertLevel.CRITICAL if severity == "critical" else 
                      AlertLevel.HIGH if severity == "warning" else AlertLevel.MEDIUM,
                category=AlertCategory.SYSTEM,
                source="system_monitor",
                location="system",
                created_at=current_time,
                status=AlertStatus.ACTIVE,
                metadata=metadata or {}
            )
            
            # 添加到工作流
            alert_event = await self.workflow_service.add_alert(alert_event)
            
            # 缓存告警
            self.system_alerts_cache[alert_id] = alert_event
            self.system_alert_cooldowns[cooldown_key] = current_time
            
            # 发送通知
            await self.notification_service.send_alert_notifications(alert_event)
            
            # 更新统计
            self.performance_stats['alerts_processed'] += 1
            
            logger.info(f"创建系统告警: {alert_type}, 严重程度: {severity}")
            return alert_id
            
        except Exception as e:
            logger.error(f"创建系统告警失败: {e}")
            return ""
    
    async def create_performance_alert(self, metric_name: str, current_value: float, 
                                     threshold: float, unit: str = "%") -> str:
        """创建性能告警"""
        severity = "critical" if current_value > threshold * 1.2 else "warning"
        
        message = f"{metric_name}达到{current_value:.1f}{unit}，超过阈值{threshold:.1f}{unit}"
        
        metadata = {
            "metric_name": metric_name,
            "current_value": current_value,
            "threshold": threshold,
            "unit": unit,
            "alert_category": "performance"
        }
        
        return await self.create_system_alert(
            alert_type=f"performance_{metric_name.lower().replace(' ', '_')}",
            message=message,
            severity=severity,
            metadata=metadata
        )
    
    async def create_stream_alert(self, camera_id: str, alert_type: str, message: str, 
                                severity: str = "warning") -> str:
        """创建流处理告警"""
        metadata = {
            "camera_id": camera_id,
            "stream_alert_type": alert_type,
            "alert_category": "stream_processing"
        }
        
        full_message = f"摄像头 {camera_id}: {message}"
        
        return await self.create_system_alert(
            alert_type=f"stream_{alert_type}",
            message=full_message,
            severity=severity,
            metadata=metadata
        )
    
    async def create_ai_processing_alert(self, algorithm: str, error_message: str, 
                                       camera_id: Optional[str] = None) -> str:
        """创建AI处理告警"""
        metadata = {
            "algorithm": algorithm,
            "error_message": error_message,
            "alert_category": "ai_processing"
        }
        
        if camera_id:
            metadata["camera_id"] = camera_id
            message = f"AI算法 {algorithm} 在摄像头 {camera_id} 处理时出错: {error_message}"
        else:
            message = f"AI算法 {algorithm} 处理出错: {error_message}"
        
        return await self.create_system_alert(
            alert_type=f"ai_{algorithm}",
            message=message,
            severity="warning",
            metadata=metadata
        )
    
    async def create_resource_alert(self, resource_type: str, usage_percent: float, 
                                  threshold: float) -> str:
        """创建资源使用告警"""
        severity = "critical" if usage_percent > 95 else "warning"
        
        message = f"{resource_type}使用率达到{usage_percent:.1f}%，超过阈值{threshold:.1f}%"
        
        metadata = {
            "resource_type": resource_type,
            "usage_percent": usage_percent,
            "threshold": threshold,
            "alert_category": "resource_usage"
        }
        
        return await self.create_system_alert(
            alert_type=f"resource_{resource_type.lower()}",
            message=message,
            severity=severity,
            metadata=metadata
        )
    
    async def get_recent_system_alerts(self, severity: Optional[str] = None, 
                                     limit: int = 100) -> List[Dict[str, Any]]:
        """获取最近的系统告警"""
        try:
            # 从工作流服务查询系统告警
            query = AlertQuery(
                categories=[AlertCategory.SYSTEM],
                start_time=datetime.now() - timedelta(hours=24),
                limit=limit
            )
            
            if severity:
                level_map = {
                    "critical": AlertLevel.CRITICAL,
                    "warning": AlertLevel.HIGH,
                    "info": AlertLevel.MEDIUM
                }
                if severity in level_map:
                    query.levels = [level_map[severity]]
            
            alerts = await self.workflow_service.query_alerts(query)
            
            return [
                {
                    "alert_id": alert.alert_id,
                    "title": alert.title,
                    "message": alert.message,
                    "severity": alert.level.value if hasattr(alert.level, 'value') else str(alert.level),
                    "created_at": alert.created_at.isoformat(),
                    "status": alert.status.value if hasattr(alert.status, 'value') else str(alert.status),
                    "metadata": alert.metadata
                }
                for alert in alerts
            ]
            
        except Exception as e:
            logger.error(f"获取系统告警失败: {e}")
            return []
    
    async def resolve_system_alert(self, alert_id: str, resolution_note: str = "系统自动解决") -> bool:
        """解决系统告警"""
        try:
            success = await self.workflow_service.resolve_alert(alert_id, "system", resolution_note)
            
            # 从缓存中移除
            if alert_id in self.system_alerts_cache:
                del self.system_alerts_cache[alert_id]
            
            return success
            
        except Exception as e:
            logger.error(f"解决系统告警失败: {e}")
            return False
    
    async def batch_resolve_system_alerts(self, alert_type: str, 
                                        resolution_note: str = "批量解决") -> int:
        """批量解决指定类型的系统告警"""
        try:
            resolved_count = 0
            
            # 查询指定类型的活跃告警
            query = AlertQuery(
                categories=[AlertCategory.SYSTEM],
                statuses=[AlertStatus.ACTIVE, AlertStatus.ACKNOWLEDGED],
                limit=1000
            )
            
            alerts = await self.workflow_service.query_alerts(query)
            
            for alert in alerts:
                if alert.metadata.get("alert_category") == alert_type:
                    if await self.resolve_system_alert(alert.alert_id, resolution_note):
                        resolved_count += 1
            
            logger.info(f"批量解决系统告警: {resolved_count} 个 {alert_type} 类型告警")
            return resolved_count
            
        except Exception as e:
            logger.error(f"批量解决系统告警失败: {e}")
            return 0
    
    async def get_system_alert_statistics(self) -> Dict[str, Any]:
        """获取系统告警统计"""
        try:
            # 获取最近24小时的系统告警
            query = AlertQuery(
                categories=[AlertCategory.SYSTEM],
                start_time=datetime.now() - timedelta(hours=24),
                limit=1000
            )
            
            alerts = await self.workflow_service.query_alerts(query)
            
            # 统计各类告警
            stats = {
                "total_alerts": len(alerts),
                "active_alerts": len([a for a in alerts if a.status == AlertStatus.ACTIVE]),
                "resolved_alerts": len([a for a in alerts if a.status == AlertStatus.RESOLVED]),
                "alert_types": {},
                "severity_distribution": {
                    "critical": 0,
                    "warning": 0,
                    "info": 0
                },
                "hourly_trend": {}
            }
            
            # 按类型统计
            for alert in alerts:
                alert_category = alert.metadata.get("alert_category", "unknown")
                if alert_category not in stats["alert_types"]:
                    stats["alert_types"][alert_category] = 0
                stats["alert_types"][alert_category] += 1
                
                # 按严重程度统计
                if alert.level == AlertLevel.CRITICAL:
                    stats["severity_distribution"]["critical"] += 1
                elif alert.level == AlertLevel.HIGH:
                    stats["severity_distribution"]["warning"] += 1
                else:
                    stats["severity_distribution"]["info"] += 1
                
                # 按小时统计
                hour = alert.created_at.strftime("%H:00")
                if hour not in stats["hourly_trend"]:
                    stats["hourly_trend"][hour] = 0
                stats["hourly_trend"][hour] += 1
            
            return stats
            
        except Exception as e:
            logger.error(f"获取系统告警统计失败: {e}")
            return {}
    
    def clear_alert_cooldowns(self):
        """清除告警冷却时间（用于测试或紧急情况）"""
        self.system_alert_cooldowns.clear()
        logger.info("已清除所有告警冷却时间")
    
    async def test_system_alert(self, alert_type: str = "test") -> str:
        """测试系统告警功能"""
        return await self.create_system_alert(
            alert_type=alert_type,
            message="这是一个测试告警，用于验证系统告警功能是否正常工作",
            severity="info",
            metadata={"test": True, "timestamp": datetime.now().isoformat()}
        )

# 全局告警管理服务实例
alert_management_service = AlertManagementService()